#include "KamaCoder.h"
using namespace std;

void KamaCoder102::dfs(vector<vector<int>>& grid, int x, int y) {
  // 把当前陆地赋值为海洋
  grid[x][y] = 2;
  count++;
  // 遍历四个方向
  for (int i = 0; i < 4; i++) {
    int nextx = x + dir[i][0];
    int nexty = y + dir[i][1];
    // 越界检查
    if (nextx < 0 || nexty < 0 || nextx >= grid.size() ||
        nexty >= grid[0].size())
      continue;
    if (grid[nextx][nexty] == 1) {
      // 相连是陆地的话，再进行递归
      dfs(grid, nextx, nexty);
    }
  }
}
// 广度搜索
void KamaCoder102::bfs(vector<vector<int>>& grid, int x, int y) {
  queue<pair<int, int>> que;
  que.push({x, y});
  grid[x][y] = 2;
  count++;
  while (!que.empty()) {
    pair<int, int> cur = que.front();
    que.pop();
    int nextx = cur.first;
    int nexty = cur.second;
    // 越界检查
    if (nextx < 0 || nexty < 0 || nextx >= grid.size() ||
        nexty >= grid[0].size())
      continue;
    if (grid[nextx][nexty] == 1) {
      grid[nextx][nexty] = 2;
      count++;
      que.push({nextx, nexty});
    }
  }
}
int KamaCoder102::run() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> grid(n, vector<int>(m));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> grid[i][j];
    }
  }
  // 与左右边界相连的岛屿
  for (int i = 0; i < n; i++) {
    // if(grid[i][0] == 1) dfs(grid,i,0);
    // if(grid[i][m-1] == 1) dfs(grid,i,m-1);
    if (grid[i][0] == 1) bfs(grid, i, 0);
    if (grid[i][m - 1] == 1) bfs(grid, i, m - 1);
  }
  // 与上下边界相连的岛屿
  for (int i = 0; i < m; i++) {
    // if(grid[0][i] == 1) dfs(grid,0,i);
    // if(grid[n-1][i] == 1) dfs(grid,n-1,i);
    if (grid[0][i] == 1) bfs(grid, 0, i);
    if (grid[n - 1][i] == 1) bfs(grid, n - 1, i);
  }
  count = 0;
  // 把边界相接壤的岛屿都处理完后，再重新遍历一次网格，即可得到孤岛
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (grid[i][j] == 1) grid[i][j] = 0;
      if (grid[i][j] == 2) grid[i][j] = 1;
      // if(grid[i][j]==1) dfs(grid,i,j);
    }
  }
  // 输出
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cout << grid[i][j] << " ";
    }
    cout << endl;
  }
  return 0;
}